package revontuli.aMHD.datamanagement;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import revontuli.aMHD.dataclasses.Stop;

public class StopXMLHandler extends DefaultHandler {
	private StringBuffer buffer = new StringBuffer();
	private ArrayList<Stop> stopList;
	private Stop stop;
	private Stop.StopPlatform platform;
	
	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
		buffer.setLength(0);
		
		if (localName.equals("stoplist")) {
			stopList = new ArrayList<Stop>();
		} else if (localName.equals("stop")) {
			stop = new Stop(Integer.parseInt(atts.getValue("stop_id")));
		} else if (localName.equals("platformlist")) {
			stop.platforms = new ArrayList<Stop.StopPlatform>();
		} else if (localName.equals("platform")) {
			platform = stop.new StopPlatform(Integer.parseInt(atts.getValue("platform_id")));
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) {
		if (localName.equals("stop")) {
			stopList.add(stop);
		} else if (localName.equals("stop_name")) {
			stop.name = buffer.toString();
		} else if (localName.equals("stop_latitude")) {
			stop.location.setLatitude(Double.parseDouble(buffer.toString()));
		} else if (localName.equals("stop_longitude")) {
			stop.location.setLongitude(Double.parseDouble(buffer.toString()));
		} else if (localName.equals("stop_zone")) {
			stop.zone = Integer.parseInt(buffer.toString());
		} else if (localName.equals("stop_ondemand")) {
			stop.ondemand = (Integer.parseInt(buffer.toString()) == 1)?true:false;
		} else if (localName.equals("stop_active")) {
			stop.active = (Integer.parseInt(buffer.toString()) == 1)?true:false;
		} else if (localName.equals("stop_revision")) {
			stop.stop_revision = Integer.parseInt(buffer.toString());
		} else if (localName.equals("platform")) {
			stop.platforms.add(platform);
		} else if (localName.equals("platform_latitude")) {
			platform.location.setLatitude(Double.parseDouble(buffer.toString()));
		} else if (localName.equals("platform_longitude")) {
			platform.location.setLongitude(Double.parseDouble(buffer.toString()));
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length) {
		buffer.append(ch, start, length);
	}
	
	public ArrayList<Stop> retrieveStopList() {
		return stopList;
	}

}
